Grokking Amazon Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Amazon Easy Problems
Redistribute Characters to Make All Strings Equal (easy)
Solution: Redistribute Characters to Make All Strings Equal
Longest Common Prefix (easy)
Solution: Longest Common Prefix
Make Array Zero by Subtracting Equal Amounts (easy)
Solution: Make Array Zero by Subtracting Equal Amounts
Leaf-Similar Trees (easy)
Solution: Leaf-Similar Trees
Path Crossing (easy)
Solution: Path Crossing
Special Array With X Elements Greater Than or Equal X (easy)
Solution: Special Array With X Elements Greater Than or Equal X
Relative Sort Array (easy)
Solution: Relative Sort Array
Transpose Matrix (easy)
Solution: Transpose Matrix
Find Common Characters (easy)
Solution: Find Common Characters
Fizz Buzz (easy)
Solution: Fizz Buzz
Increasing Order Search Tree (easy)
Solution: Increasing Order Search Tree
Largest Odd Number in String (easy)
Solution: Largest Odd Number in String
Best Time to Buy and Sell (easy)
Solution: Best Time to Buy and Sell Stock
Take Gifts From the Richest Pile(easy)
Solution: Take Gifts From the Richest Pile
Remove Duplicates from Sorted List (easy)
Solution: Remove Duplicates from Sorted List
Maximum Length of Subarray With Positive Product (medium)
Solution: Maximum Length of Subarray With Positive Product
Largest Submatrix With Rearrangements (medium)
Solution: Largest Submatrix With Rearrangements
Count the Number of Good Subarrays (medium)
Solution: Count the Number of Good Subarrays
Minimum Suffix Flips (medium)
Solution: Minimum Suffix Flips
Minimum Number of Operations to Make Array Empty (medium)
Solution: Minimum Number of Operations to Make Array Empty
Next Greater Element II (medium)
Solution: Next Greater Element II
Make Sum Divisible by P (medium)
Solution: Make Sum Divisible by P
Rotting Oranges (medium)
Solution: Rotting Oranges
Minimum Deletions to Make Character Frequencies Unique (medium)
Solution: Minimum Deletions to Make Character Frequencies Unique
Minimum Adjacent Swaps to Make a Valid Array (medium)
Solution: Minimum Adjacent Swaps to Make a Valid Array
Reverse Integer (medium)
Solution: Reverse Integer
Maximize Distance to Closest Person (medium)
Solution: Maximize Distance to Closest Person
Split Linked List in Parts (medium)
Solution: Split Linked List in Parts
Maximum Difference Between Node and Ancestor (medium)
Solution: Maximum Difference Between Node and Ancestor
Deepest Leaves Sum (medium)
Solution: Deepest Leaves Sum
The kth Factor of n (medium)
Solution: The kth Factor of n
Coin Change II (medium)
Solution: Coin Change II
Sum of Subarray Minimums (medium)
Solution: Sum of Subarray Minimums
Valid Sudoku (medium)
Solution: Valid Sudoku
Longest Increasing Subsequence (medium)
Solution: Longest Increasing Subsequence
Next Permutation (medium)
Solution: Next Permutation
Subsets (medium)
Solution: Subsets
Combination Sum (medium)
Solution: Combination Sum
Number of Provinces (medium)
Solution: Number of Provinces
Number of Islands (medium)
Solution: Number of Islands
Constrained Subsequence Sum (hard)
Solution: Constrained Subsequence Sum
Number of Valid Subarrays (hard)
Solution: Number of Valid Subarrays
Count Vowels Permutation (hard)
Solution: Count Vowels Permutation
Concatenated Words (hard)
Solution: Concatenated Words
Minimum Replacements to Sort the Array (hard)
Solution: Minimum Replacements to Sort the Array
Count All Valid Pickup and Delivery Options (hard)
Solution: Count All Valid Pickup and Delivery Options
Length of the Longest Valid Substring (hard)
Solution: Length of the Longest Valid Substring
Count Array Pairs Divisible by K (hard)
Solution: Count Array Pairs Divisible by K
Word Ladder (hard)
Solution: Word Ladder
Path with Maximum Sum (hard)
Solution: Path with Maximum Sum
Solution: Redistribute Characters to Make All Strings Equal

Problem Statement

Given an array of strings words, return true if you can make all strings equal in words array by performing any number of swap operations. Otherwise, return false.

In one swap operation, you can pick any two indices i and j, and move any characters from words[i] to any position of the words[j].

Examples

  • Example 1:

    • Input: words = ["aaa","bbb","ccc", "abc"]
    • Expected Output: true
    • Justification: Each string has 3 characters of a single type, and the last string has all 3 characters. We can redistribute the characters to form a string like "abc" making the distribution equal.
  • Example 2:

    • Input: words = ["ab","bc","cd","de","ea"]
    • Expected Output: false
    • Justification: The characters cannot be redistributed to make all strings equal because all characters appear only twice, making equal distribution impossible.
  • Example 3:

    • Input: words = ["zzx","xzz","zxz"]
    • Expected Output: true
    • Justification: We can redistribute characters to have each string contain one "x" and two "z"s, like "zzx", "xzz", "zxz", maintaining equal distribution.

Solution

To solve this problem, we'll focus on counting the frequency of each character across all strings and then check if these frequencies can be divided evenly by the number of strings. This approach works because, for the characters to be distributable equally, the total occurrences of each character must be a multiple of the number of strings. This method is effective as it simplifies the problem to a straightforward mathematical check, avoiding the need for complex manipulations or redistributions of the characters.

Our strategy will involve two main steps: first, creating a comprehensive count of each character's appearances across all strings. This is achieved by iterating through each string and incrementing the count for each character. Second, we'll verify if each character's total count is divisible by the number of strings. If all characters pass this test, it implies an equal distribution is possible; otherwise, it is not. This method is chosen for its efficiency and simplicity, directly addressing the problem's core requirement without unnecessary complexity.

Step-by-step algorithm

  1. Initialize a Character Frequency Map: Create an empty map (or dictionary) to keep track of the frequency of each character across all the strings. The key will be the character, and the value will be the count of how many times that character appears.

  2. Count Character Frequencies: Iterate over each string in the input array. For each string, iterate over each character and update the character frequency map by increasing the count for each character.

  3. Check for Equal Distribution:

    • Calculate the number of strings in the input array. This will be used to check if a character can be evenly distributed.
    • Iterate over the values in the character frequency map. For each frequency value, check if it is divisible by the number of strings. If any frequency is not divisible, return false, indicating that an equal distribution is not possible.
    • If all frequencies are divisible by the number of strings, return true.

Algorithm Walkthrough

Input: ["aaa","bbb","ccc", "abc"]

  • Step 1: Initialize a character frequency map. It will be empty initially: {}.

  • Step 2: Count character frequencies.

    • For the first string "aaa", update the map: {'a': 3}.
    • For the second string "bbb", update the map: {'a': 3, 'b': 3}.
    • For the third string "ccc", update the map: {'a': 3, 'b': 3, 'c': 3}.
    • For the fourth string "abc", update the map: {'a': 4, 'b': 4, 'c': 4}.
  • Step 3: Check for equal distribution.

    • The number of strings is 4.
    • Check divisibility for each character frequency:
      • {'a': 4}: 4 % 4 == 0, so 'a' can be evenly distributed.
      • {'b': 4}: 4 % 4 == 0, so 'b' can be evenly distributed.
      • {'c': 4}: 4 % 4 == 0, so 'c' can be evenly distributed.
    • Since all characters can be evenly distributed, return true.
Image

Code

Java

. . . .

Complexity Analysis

Time Complexity: The time complexity of the algorithm is , where N is the number of strings in the input array and M is the average length of these strings. This complexity arises because the algorithm iterates through each character of each string to count the frequency of characters.

Space Complexity: The space complexity of the algorithm is , where K is the number of unique characters across all strings. This space is required to store the frequency of each character in a hash map or dictionary. The maximum size of this map depends on the size of the character set used in the strings.

Redistribute Characters to Make All Strings Equal (easy)
Longest Common Prefix (easy)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-step algorithm

Algorithm Walkthrough

Code

Complexity Analysis